package org.ruoyi.common.dhuman.rpc;

import org.ruoyi.common.utils.MD5Util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * TTS语音合成工具类
 */
public class VideoClient {
    
    private static final String API_URL = "https://api.deepsound.cn/v1.0/tts";
    
    /**
     * 根据curl规则发送TTS请求
     * 
     * @param requestBody 请求体JSON字符串
     * @param appid 应用ID
     * @param sign 签名
     * @param timestamp 时间戳
     * @return 响应结果
     * @throws Exception 网络请求异常
     */
    public static String sendTtsRequest(String requestBody, String appid, String sign, long timestamp)
            throws Exception {
        
        URL url = new URL(API_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        // 设置请求方法
        connection.setRequestMethod("POST");
        
        // 设置请求头
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("X-Deepsound-Sign", "MD5 " + sign);
        connection.setRequestProperty("X-Deepsound-Appid", appid);
        connection.setRequestProperty("X-Deepsound-Timestamp", String.valueOf(timestamp));
        
        // 设置允许输出
        connection.setDoOutput(true);
        
        // 发送请求体
        try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
            byte[] postData = requestBody.getBytes(StandardCharsets.UTF_8);
            outputStream.write(postData);
        }
        
        // 读取响应
        int responseCode = connection.getResponseCode();
        StringBuilder response = new StringBuilder();
        
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                responseCode >= 200 && responseCode < 300 ? 
                connection.getInputStream() : connection.getErrorStream(), 
                StandardCharsets.UTF_8))) {
            
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        
        return response.toString();
    }

	public static void main(String[] args) throws Exception {
		String appid = "L14OHuMe";
		Long timestamp = System.currentTimeMillis()/1000;
		String appscret = "2be93310b9da883e156bd25f282d1bc5";

		String sign = MD5Util.GetMD5Code(appid + timestamp + appscret).toUpperCase();
		System.out.println("request =========================");
		System.out.println("appid=" + appid + "&timestamp=" + timestamp + "&sign=" + sign);

		String response = sendTtsRequest(
			"",
			appid,
			sign,
			timestamp
		);
		System.out.println("response ========================");
		System.out.println(response);
	}
}
